import os.path

import requestNovelsLib


def appIniFileStrToLenStr(srcDict: dict[int, list[str]], srcStrArray: list[str]):
	"""
	根据 srcStrArray 中的字符进行词典追加，关键字为字符长度
	:param srcDict: 被追加的词典
	:param srcStrArray: 追加的字符串列表
	"""
	strKey = ""
	strLen = 0
	keyArray: list[str] = None
	for strKey in srcStrArray:
		strLen = len(strKey)
		keyArray = srcDict.get(strLen)
		if keyArray is None:
			keyArray = []
			srcDict[strLen] = keyArray
		keyArray.append(strKey)


def getPathIniFileStrDic(paths: list[str]) -> dict[str, list[str]]:
	"""
	返回以为文件路径为关键字，内容为值的配值对，其中值不重复的关键字
	:param paths: 多个路径
	:return:  文件路径为关键字，内容为值的配值对的词典对象，失败返回 None
	"""
	if paths is None or len(paths) == 0:
		return None
	paths = requestNovelsLib.strListreduce(paths)
	oldList: list[str] = []
	result: dict[int, list[str]] = {}
	readList: list[str] = None
	readCount = 0
	fileKeyList: list[str] = []
	for filePath in paths:
		filePaths = requestNovelsLib.getPathFilesNames(filePath)
		for fileName in filePaths:
			fileKeyList = []
			print(f"============\n\t获取目标文件 ： {fileName}   -> 信息")
			readList = requestNovelsLib.readFile(fileName).split("\n")
			for checkStr in readList:
				checkStr = requestNovelsLib.strRemoveSpaces(checkStr)
				if not requestNovelsLib.strListIsKey(checkStr, oldList):
					oldList.append(checkStr)
					fileKeyList.append(checkStr)
			readCount = len(fileKeyList)
			if readCount > 0:
				result[fileName] = fileKeyList
				print(f"\t\t目标关键字数量 ： {readCount}   -> ( {fileName} )信息\n=========")
				requestNovelsLib.writeFile("\n".join(fileKeyList) + "\n", fileName)
			else:
				print(f"\t\t ( {fileName} )信息数量 ： {readCount} -> 正在执行清空操作\n=========")
				## requestNovelsLib.writeFile("", fileName)
				requestNovelsLib.removeFile(fileName)
	if len(result) > 0:
		return result
	return None


def getPathIniFileStrToLenStr(paths: list[str], hasKeyList: list[str]) -> dict[int, list[str]]:
	"""
	读取路径下的所有文件，并且返回属于文件的关键字，以 '\n' 为分隔符的所有字符串
	:param paths: 多个路径
	:param hasKeyList: 存在的子字符串列表
	:return: 返回以关键字的长度为关键字的词典，失败返回 None
	"""
	if paths is None or len(paths) == 0:
		return None
	paths = requestNovelsLib.strListreduce(paths)
	result: dict[int, list[str]] = {}
	## 字符长度
	strLen = 0
	checkKey = ""
	exisKey = ""
	filePath = ""
	fileName = ""
	jmp = False
	readList: list[str] = None
	writeUpdatList: list[str] = []
	readCount = 0
	exSize = 0
	## 排重
	for filePath in paths:
		filePaths = requestNovelsLib.getPathFilesNames(filePath)
		for fileName in filePaths:
			print(f"\t获取源文件 ： {fileName}   -> 信息")
			readList = requestNovelsLib.readFile(fileName).replace("\r", "").split("\n")
			for exisKey in readList:
				exisKey = requestNovelsLib.strRemoveSpaces(exisKey)
				strLen = len(exisKey)
				if strLen == 0 or requestNovelsLib.strListHasKey(exisKey, hasKeyList):
					continue
				exisArray = result.get(strLen)
				if exisArray is None:
					result[strLen] = [exisKey]
					writeUpdatList.append(exisKey)
					readCount += 1
				elif not requestNovelsLib.strListIsKey(exisKey, exisArray):
					exisArray.append(exisKey)
					writeUpdatList.append(exisKey)
					readCount += 1
				else:
					...
			readCount = len(writeUpdatList)
			print(f"\t\t目标关键字数量 ： {readCount}   -> ( {fileName} )信息")
			if readCount > 0:
				writeUpdatList.sort(key=len)
				requestNovelsLib.writeFile("\n".join(writeUpdatList) + "\n", fileName)
				writeUpdatList = []
			else:
				requestNovelsLib.writeFile("\n", fileName)
				print(f"\t\t ( {fileName} )没有预留关键字，正在执行清空操作\n=========")
			writeUpdatList = []
	return result


def getPathIniFileStrToStrArray(paths: list[str]) -> list[str]:
	"""
	从路径当中获取所有关键字
	区分子字符串
	:param paths: 多个文件路径
	:return: 不重复的关键字列表
	"""
	if paths is None or len(paths) == 0:
		return None
	paths = requestNovelsLib.strListreduce(paths)
	result: list[str] = []
	appendCount = 0
	buffList: list[str] = None
	wriiteBuffList: list[str] = None
	## 排重
	for filePath in paths:
		filePaths = requestNovelsLib.getPathFilesNames(filePath)
		for fileName in filePaths:
			wriiteBuffList = []
			print(f"\t获取源文件 ： {fileName}   -> 信息")
			buffList = getFilterFileKey(fileName)
			for item in buffList:
				if not requestNovelsLib.strListHasKey(item, result):
					result.append(item)
					wriiteBuffList.append(item)
					appendCount += 1
			i = len(wriiteBuffList)
			if i == 0:
				requestNovelsLib.writeFile("\n", fileName)
				print(f"\t不存在子字符串关键字 ：\n\t\t{fileName}\n\t\t-> 清空该路径")
			else:
				wriiteBuffList = sorted(wriiteBuffList)
				wriiteBuffList = sorted(wriiteBuffList, key=len)
				cont = ""
				for item in wriiteBuffList:
					cont = f"{cont}{item}\n"
				requestNovelsLib.writeFile(cont, fileName)
				print(f"\t录入子字符串关键字 ：\n\t\t{fileName}\n\t\t-> 信息( {i} / {len(buffList)} )")
	if len(result) == 0:
		return None
	return sorted(result, key=len)


def getFilterFileKey(fileName):
	readList = requestNovelsLib.readFile(fileName).split("\n")
	result: list[str] = []
	for appendKey in readList:
		appendKey = requestNovelsLib.strRemoveSpaces(appendKey)
		strLen = len(appendKey)
		if strLen != 0:
			result.append(appendKey)
	return result


def upDataFile(filePath: list[str]):
	readBuffKeys: list[str] = []
	currentList: list[str] = []
	currentStr: list[str] = []
	writeFileCont = ""
	for filePath in readKeyWordFiles:
		filePaths = requestNovelsLib.getPathFilesNames(filePath)
		for fileName in filePaths:
			currentList = requestNovelsLib.readFile(fileName).split("\n")
			for var in currentList:
				var = requestNovelsLib.strRemoveSpaces(var)
				if len(var) == 0 or requestNovelsLib.strListHasKey(var, readBuffKeys):
					continue
				currentStr.append(var)
				readBuffKeys.append(var)
			if len(currentStr) == 0:
				continue
			currentStr.sort(key=len)
			for var in currentStr:
				writeFileCont = f"{writeFileCont}{var}\n"
			print(f"写入文件({len(currentStr)}) : {fileName}")
			requestNovelsLib.writeFile(writeFileCont, fileName)
			currentStr = []
			writeFileCont = ""


def listToStr(listObj, jion) -> str:
	resultStr: str = ""
	for obj in listObj:
		resultStr = f"{resultStr}{obj}{jion}"
	return resultStr


def removeNullDir(pathBuff) -> list[str]:
	result: list[str] = pathBuff[:]
	for resourceDir in pathBuff:
		if os.path.exists(resourceDir) is False:
			result.remove(resourceDir)
			print(f"不存在目录 : {resourceDir}")
			continue
		pathInfo = requestNovelsLib.PathInfo(resourceDir)
		dirs = pathInfo.getDirs()
		if len(dirs) > 0:
			for checkDir in dirs:
				path_files_names = requestNovelsLib.getPathFilesNames(checkDir)
				if len(path_files_names) == 0:
					for fileName in requestNovelsLib.removePath(checkDir):
						print(f"删除 : {fileName}")
			continue
	return result


def todoFilter(subStrMapIterator, hasKeyList):
	buffDict: [str, list[str]] = {}
	resultMap: [str, list[str]] = {}
	name = ""
	for file, conten in subStrMapIterator:
		conten = fileFilterKey(buffDict, hasKeyList, file)
		if buffDict.get(file) is None:
			requestNovelsLib.removeFile(file)
			print(f"\t文件 {file} 没有获取到对应的关键字-》执行删除")
		else:
			resultMap[file] = conten
	return resultMap


def fileFilterKey(buffDict, hasKeyList, file) -> list[str]:
	newArrayKey = []
	conten = requestNovelsLib.readFile(file).split("\n")
	for name in conten:
		readKeyWordFiles = requestNovelsLib.strRemoveSpaces(str(name))
		if len(readKeyWordFiles) == 0 or requestNovelsLib.strListHasKey(readKeyWordFiles, hasKeyList):
			continue
		newArrayKey.append(readKeyWordFiles)
	if len(newArrayKey) > 0:
		newArrayKey = sorted(newArrayKey, key=len)
		buffDict[file] = newArrayKey
		content = ""
		for item in newArrayKey:
			content = f"{content}{item}\n"
		requestNovelsLib.writeFile(content, file)
	return newArrayKey


if __name__ == '__main__':
	argvDict = requestNovelsLib.initParamArgs()
	
	## 获取被删除关键字的文件
	sourceKeyFilePaths = argvDict.get("d")
	
	readKeyWordFiles = argvDict.get("")
	if readKeyWordFiles is None or len(readKeyWordFiles) == 0:
		print("不存在重新修复的文件")
	else:
		if sourceKeyFilePaths:
			updataList: list[str] = []
			for readKeyWordFilesFile in readKeyWordFiles:
				if requestNovelsLib.strListIsKey(readKeyWordFilesFile, sourceKeyFilePaths):
					continue
				updataList.append(readKeyWordFilesFile)
			readKeyWordFiles = updataList
		upDataFile(readKeyWordFiles)
	print("开始配置选项功能")
	
	if sourceKeyFilePaths is None or len(sourceKeyFilePaths) == 0:
		print("找不到目标路径")
		exit(-1)
	parmBuffList = sourceKeyFilePaths[:]
	sourceKeyFilePaths = removeNullDir(parmBuffList)
	
	## 关键字文件
	todoKeysMap: [str, list[str]] = getPathIniFileStrDic(sourceKeyFilePaths)
	if todoKeysMap is None:
		print("没有目标的路径(路径不存在文件)")
		exit(-2)
	
	todoKeysMapIterator = todoKeysMap.items()
	## 获取子字符串关键字
	hasKeyFilePaths = argvDict.get("h")
	hasRemveSubStrItem = False
	hasKeyList: list[str] = []
	if hasKeyFilePaths is not None and len(hasKeyFilePaths) > 0:
		hasKeyList = getPathIniFileStrToStrArray(hasKeyFilePaths)
		todoKeysMap = todoFilter(todoKeysMapIterator, hasKeyList)
		if len(todoKeysMap) == 0:
			print("没有配置存在关键字的配置路径")
			exit(0)
		todoKeysMapIterator = todoKeysMap.items()
		hasRemveSubStrItem = True
	else:
		print("没有配置存在关键字的配置路径")
		...
	print("==========>")
	
	## 存储完整排除的关键字
	fullKeyWordMap: {int, list[str]} = {}
	## 获取命令行输入完整的关键字
	compileKeyWord: list[str] = argvDict.get("k")
	if compileKeyWord is not None and len(compileKeyWord) > 0:
		appIniFileStrToLenStr(fullKeyWordMap, compileKeyWord)
	
	## 从路径中获取子关键字
	subStrKeyWordPaths = argvDict.get("s")
	if subStrKeyWordPaths is None or len(subStrKeyWordPaths) == 0:
		print("不存在删除关键字的配置路径")
	else:
		strLenFullKeyWorkMap = getPathIniFileStrToLenStr(subStrKeyWordPaths, hasKeyList)
		## 如果从文件获取到一些内容，则开始加入到映射当中
		if len(strLenFullKeyWorkMap) > 0:
			item = strLenFullKeyWorkMap.items()
			for key, values in item:
				if fullKeyWordMap.get(key) is None:
					fullKeyWordMap[key] = values
				else:
					for value in values:
						fullKeyWordMap[key].append(value)
	## 没有需要删除的完整关键字，即可写入文件
	if fullKeyWordMap is None or len(fullKeyWordMap) == 0:
		print("没有目标的路径(路径不存在文件)")
		exit(-2)
	
	## 比较完毕的整个映射内容
	writeContentArrayKeys: list[str] = []
	## 关键字长度
	keyStrLen = 0
	## 映射当中的数组
	exisKeyArray: list[str] = None
	buffList: list[str] = []
	for filePath, fileContents in todoKeysMapIterator:
		## 读取所有文件
		for fileKey in fileContents:
			keyStrLen = len(fileKey)
			if keyStrLen == 0:
				continue
			exisKeyArray = fullKeyWordMap.get(keyStrLen)
			## 检测关键字是否存在指定字符串数组当中
			if exisKeyArray is not None and requestNovelsLib.strListIsKey(fileKey, exisKeyArray):
				continue
			writeContentArrayKeys.append(fileKey)
		
		if len(writeContentArrayKeys) > 0:
			writeContentArrayKeys = sorted(writeContentArrayKeys, key=len)
			writeContent = ""
			for item in writeContentArrayKeys:
				writeContent = f"{writeContent}{item}\n"
			requestNovelsLib.writeFile(writeContent, filePath)
			writeContentArrayKeys.clear()
		else:
			requestNovelsLib.removeFile(filePath)
			print(f"\t\t ( {filePath} )没有预留关键字，正在执行删除操作\n=========")
	removeNullDir(parmBuffList)
